package com.jiaok.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiaok.config.securityHandler.FailedAuthenticationEntryPoint;
import com.jiaok.utils.RequestWrapper;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 验证码过滤器，添加在最前面， 先检测验证码，如果验证码都不对，直接返回
 * @Author jiaok
 * @Date 2023/5/11 15:25
 */
@Component
public class CaptchaFilter  extends OncePerRequestFilter {

    @Resource
    private FailedAuthenticationEntryPoint failedAuthenticationEntryPoint;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //首先确定当前的请求为登录请求，并不是所有的请求都包含验证码
        String requestURI = request.getRequestURI();
        if (("/user/login").equals(requestURI)&&request.getMethod().equals("POST")){
            //进入验证码验证步骤
            RequestWrapper requestWrapper = verificatCaptcha(request, response);
            //不是登录请求，直接放行
            filterChain.doFilter(requestWrapper,response);
        }else {
            //不是登录请求，直接放行
            filterChain.doFilter(request,response);
        }
    }

    /**
     * 校验验证码是否正确
     * @param request
     * @param response
     * @return
     */
    private RequestWrapper verificatCaptcha(HttpServletRequest request,HttpServletResponse response) {
        String code = request.getParameter("code");
        try {
            RequestWrapper requestWrapper = new RequestWrapper(request);
            BufferedReader streamReader = null;
            streamReader = new BufferedReader( new InputStreamReader(requestWrapper.getInputStream(), "UTF-8"));

            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }

            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            code=(String) jsonObject.get("code");
    //            Map<String, String> params = JSON.parseObject(responseStrBuilder.toString(), Map.class);
    //        如果验证码不正确，交由认证认证失败处理器
            if (!"111111".equals(code)){
                try {
                    failedAuthenticationEntryPoint.commence(request,response,  new AccountExpiredException(("验证码错误")));
                } catch (ServletException e) {
                    throw new RuntimeException(e);
                }
            }
            return requestWrapper;
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
